package Core

import (
	"fmt"
	"os"
	"io/ioutil"
	"encoding/json"
	"strings"
	"strconv"
)

// declare Config var
var Config *HxConfig

// declare HxConfig struct
type HxConfig struct {
	data map[string]map[string]interface {}
	fileName string
}

// Get string value
func (this *HxConfig) String(key string) string {
	keys := strings.Split(key, ".")
	if this.data[keys[0]] == nil {
		return ""
	}
	if len(keys) < 2 {
		return ""
	}
	return fmt.Sprint(this.data[keys[0]][keys[1]])
}

// Get string value with default value
func (this *HxConfig) StringOr(key string, def string) string {
	str := this.String(key)
	if str == "" {
		return def
	}
	return str
}

// Get int value
func (this *HxConfig) Int(key string) int {
	str := this.String(key)
	i, _ := strconv.ParseInt(str, 10, 64)
	return int(i)
}

// Get int value with default value
func (this *HxConfig) IntOr(key string, def int) int {
	i := this.Int(key)
	if i == 0 {
		return def
	}
	return i
}

// Get float value
func (this *HxConfig) Float(key string) float64 {
	str := this.String(key)
	i, _ := strconv.ParseFloat(str, 10,)
	return i
}

// Get float value with default value
func (this *HxConfig) FloatOr(key string, def float64) float64 {
	i := this.Float(key)
	if i == 0 {
		return def
	}
	return i
}

// Get bool value
func (this *HxConfig) Bool(key string) bool {
	str := this.String(key)
	i, _ := strconv.ParseBool(str)
	return i
}

// Get map value
// return map[string]interface{}
func (this *HxConfig) Map(key string) map[string]interface {} {
	return this.data[key]
}

// Set string value by key string
func (this *HxConfig) Set(key, value string) {
	keys := strings.Split(key, ".")
	if len(keys) < 2 {
		return
	}
	if this.data[keys[0]] == nil {
		this.data[keys[0]] = make(map[string]interface {})
	}
	this.data[keys[0]][keys[1]] = value
}

// create new *HxConfig
func newConfig(fileName string) {
	// check file
	_, e := os.Stat(fileName)
	if e != nil {
		panic(e)
	}
	// read file bytes
	var bytes []byte
	bytes, e = ioutil.ReadFile(fileName)
	if e != nil {
		panic(e)
	}
	// json decode
	data := make(map[string]map[string]interface {})
	e = json.Unmarshal(bytes, &data)
	if e != nil {
		panic(e)
	}
	Config = &HxConfig{}
	Config.fileName = fileName
	Config.data = data
}
